package com.origin.utils

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.os.Build
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.IntDef
import com.origin.utils.ToastUtils.showSystem
import kotlinx.coroutines.*
import java.lang.annotation.RetentionPolicy;


object ToastUtils {


    private var toastSystem: Toast? = null
    private var toastLayout: Toast? = null

    class Location(
        @AnnotationList.ToastUtilsLocation var gravity: Int,
        var xOffset: Int,
        var yOffset: Int
    )


    private var scope = CoroutineScope(Dispatchers.Default)

    //    private var lastClickTime = 0L
    private const val CLICK_INTERVAL = 2000L;

    @Synchronized
    fun showLayout(
        context: Context,
        layoutView: View, @AnnotationList.Duration duration: Int, location: Location? = null
    ) {

        if (toastLayout != null) {
            toastLayout!!.cancel()
            toastLayout!!.view=null
            toastLayout = null
            scope.cancel()
            scope = CoroutineScope(Dispatchers.Default)
        }
        toastLayout = Toast(context.applicationContext);
        toastLayout?.view = layoutView;
        toastLayout?.duration = duration
        location?.apply {
            toastLayout?.setGravity(gravity, xOffset, yOffset);
        }

        toastLayout?.show()

        scope.launch {
            // 执行协程任务
            delay(CLICK_INTERVAL)
            toastLayout?.cancel()
            toastLayout!!.view=null
            toastLayout = null
        }

    }

    fun String.showSystem(mContext: Application, @AnnotationList.Duration duration: Int) {
        showSystem(mContext, this, duration)
    }

    fun String.showSystem(
        mFragment: androidx.fragment.app.Fragment,
        @AnnotationList.Duration duration: Int
    ) {
        val self = this;
        mFragment.activity?.apply {

            showSystem(this.application, self, duration)
        }

    }

    fun showSystem(
        mContext: Application,
        text: CharSequence = "",
        @AnnotationList.Duration duration: Int = AnnotationList.LENGTH_SHORT,
        location: Location? = null
    ) {

        if (toastSystem == null) {
            @SuppressLint("ShowToast")
            toastSystem = Toast.makeText(mContext, text, duration)
        } else {
            toastSystem?.setText(text)
        }
        location?.apply {
            toastSystem?.setGravity(gravity, xOffset, yOffset);
        }
        toastSystem?.show()
    }
}